package com.muki.uri.core;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;

import com.muki.jms.JmsConsumer;
import com.muki.uri.entity.FlagUri;

/**
 * 收取url
 * @author ljh_2017
 *
 */
public class UriGetor implements UriGet {

	private final Logger log = Logger.getLogger(UriGetor.class);
	private RequestBuilder request = RequestBuilder.getInstance();
	private JmsConsumer consumer = new JmsConsumer();
	private UriRegisterationCore core = UriRegisterationCore.getInstance();
	
	
	@Override
	public void doGet(String topic,String url) {
		RequestUri r = request.getRequest();
		log.info("获取uri请求"+r);
		if(r!=null) {
			FlagUri uri = new FlagUri();
			uri.setTopic(topic);
			uri.setUri(url);
			r.setFlagUri(uri);
			core.receive(r);
		} else
			System.out.println("request 满了");
		request.releaseRequest(r);
	}

	@Override
	public void run() {
		try {
			consumer.bindQueue("urls");
			
			consumer.getConsssumer().setMessageListener(new MessageListener() {
				
				@Override
				public void onMessage(Message message) {
					if(message instanceof TextMessage) {
						try {
							String text = ((TextMessage) message).getText();
							String[] urls = text.split("__");
							doGet(urls[1].trim(),urls[0].trim());
							message.acknowledge();
						} catch (JMSException e) {
							e.printStackTrace();
						}
					}
				}
			});
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
